package top.lyjwn.todo.security.impl;

import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.aspect.Interceptor;
import org.noear.solon.core.aspect.Invocation;
import org.noear.solon.core.handle.Context;
import top.lyjwn.todo.security.ExemptToken;
import top.lyjwn.todo.security.LoginToken;
import top.lyjwn.todo.template.R;

import java.util.concurrent.atomic.AtomicReference;

public class LoginTokenInterceptor implements Interceptor {


    private LoginToken loginToken;

    public LoginTokenInterceptor() {
        //异步订阅方式，根据bean name获取Bean
        Solon.context().getBeanAsync(LoginToken.class, bean-> {
            loginToken = bean;
        });
    }

    @Override
    public Object doIntercept(Invocation inv) throws Throwable {
        AtomicReference val0 = new AtomicReference();
        ExemptToken exemptToken = inv.method().getAnnotation(ExemptToken.class);
        if (exemptToken == null) {
            Context ctx = Context.current();
            if (ctx == null) {
                return null;
            }
            String token = ctx.header("token");

            // 如果没有免除token的请求，则进行验证
            if (token == null) {
                return R.init().error(401, "未发现token");
            }
            // 如果用户查找不到，则为假的token
            if (loginToken.getLoginByToken(token) == null) {
                return R.init().error(401, "查询不到用户信息");
            }
            // 验证 token ,加密的正确性
            if (!loginToken.verify(token)) {
                return R.init().error(401, "token验证失败");
            }
        }
        val0.set(inv.invoke());
        return val0.get();
    }
}
